package com.zzyl.nursing.service.impl;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.extension.toolkit.Db;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.nursing.domain.po.Device;
import com.zzyl.nursing.domain.po.DeviceData;
import com.zzyl.nursing.mapper.DeviceDataMapper;
import com.zzyl.nursing.service.IDeviceDataService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * 设备数据Service业务层处理
 * 
 * @author alexis
 * @date 2025-06-06
 */
@Service
public class DeviceDataServiceImpl extends ServiceImpl<DeviceDataMapper, DeviceData> implements IDeviceDataService
{
    @Autowired
    private DeviceDataMapper deviceDataMapper;


    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    /**
     * 查询设备数据
     * 
     * @param id 设备数据主键
     * @return 设备数据
     */
    @Override
    public DeviceData selectDeviceDataById(Long id)
    {
        return deviceDataMapper.selectById(id);
    }

    /**
     * 查询设备数据列表
     * 
     * @param deviceData 设备数据
     * @return 设备数据
     */
    @Override
    public List<DeviceData> selectDeviceDataList(DeviceData deviceData)
    {
        return deviceDataMapper.selectDeviceDataList(deviceData);
    }

    /**
     * 新增设备数据
     * 
     * @param deviceData 设备数据
     * @return 结果
     */
    @Override
    public int insertDeviceData(DeviceData deviceData)
    {
        return deviceDataMapper.insert(deviceData);
    }

    /**
     * 修改设备数据
     * 
     * @param deviceData 设备数据
     * @return 结果
     */
    @Override
    public int updateDeviceData(DeviceData deviceData)
    {
        return deviceDataMapper.updateById(deviceData);
    }

    /**
     * 批量删除设备数据
     * 
     * @param ids 需要删除的设备数据主键
     * @return 结果
     */
    @Override
    public int deleteDeviceDataByIds(Long[] ids)
    {
        return deviceDataMapper.deleteBatchIds(Arrays.asList(ids));
    }

    /**
     * 删除设备数据信息
     * 
     * @param id 设备数据主键
     * @return 结果
     */
    @Override
    public int deleteDeviceDataById(Long id)
    {
        return deviceDataMapper.deleteById(id);
    }

    @Override
    public void insertBatch(Map<String, Object> conextMap) {

        System.out.println("dd");

        Map<String, Object> notifyData = (Map<String, Object>) conextMap.get("notify_data");

        JSONObject header = (JSONObject) notifyData.get("header");


        String iotId = header.getStr("device_id");

        Map<String, Object> body = (Map<String, Object>) notifyData.get("body");
        List service = (List) body.get("services");


        Device device = Db.lambdaQuery(Device.class).eq(Device::getIotId, iotId).one();
        List<DeviceData> deviceDataList=new ArrayList<>();

        service.forEach(s->{
            System.out.println("dd");

            Map<String, Object> server = (Map<String, Object>)s;
            LocalDateTime activeTime =  LocalDateTimeUtil.parse((CharSequence) server.get("event_time"), "yyyyMMdd'T'HHmmss'Z'");
            //日期时区转换
            LocalDateTime eventTime = activeTime.atZone(ZoneId.from(ZoneOffset.UTC))
                    .withZoneSameInstant(ZoneId.of("Asia/Shanghai"))
                    .toLocalDateTime();


            Map<String, Object> properties = (Map<String, Object>)server.get("properties");

            properties.forEach((k,v)->{
                DeviceData deviceData = new DeviceData();
                BeanUtil.copyProperties(device,deviceData);
                deviceData.setAlarmTime(eventTime);
                deviceData.setId(null);
                deviceData.setFunctionId(k);
                deviceData.setDataValue(v.toString());
                deviceData.setAccessLocation(device.getRemark());
                deviceData.setDeviceDescription(device.getDeviceDescription());
                deviceDataList.add(deviceData);
            });



        });

        saveBatch(deviceDataList);
        redisTemplate.opsForHash().put(CacheConstants.IOT_DEVICE_LAST_DATA,iotId, JSONUtil.toJsonStr(deviceDataList));




    }


    @Override
    public void deleteDeviceDataByTime() {
        LocalDateTime now = LocalDateTime.now();
        LocalDateTime preTime = now.minusDays(15);
//        preTime=now.minusMinutes(10);

        boolean remove = remove(new LambdaQueryWrapper<DeviceData>().le(DeviceData::getAlarmTime, preTime));

    }
}
